// pages/volunteer/redeem-flow.js
Page({
  data: {
    // 用户信息
    userInfo: {
      name: '晴天',
      volunteerId: '123444890',
      currentPoints: 250
    },
    
    // 商品信息
    selectedProduct: null,
    
    // 商品图片
    productImages: [],
    currentImageIndex: 0,
    
    // 兑换相关
    redeemQuantity: 1,
    canRedeem: false
  },

  onLoad(options) {
    console.log('redeem-flow页面加载，参数:', options);
    // 获取传递的商品ID
    const productId = options.productId;
    if (productId) {
      console.log('开始加载商品信息，商品ID:', productId);
      this.loadProductInfo(productId);
    } else {
      console.error('未接收到商品ID参数');
      wx.showToast({
        title: '商品信息错误',
        icon: 'none'
      });
    }
    
    this.loadUserData();
  },

  // 加载用户数据
  loadUserData() {
    const userData = wx.getStorageSync('volunteerUserData') || {};
    this.setData({
      userInfo: { ...this.data.userInfo, ...userData }
    });
    this.checkRedeemStatus();
  },

  // 加载商品信息
  loadProductInfo(productId) {
    console.log('开始加载商品信息，商品ID:', productId);
    // 模拟从服务器获取商品信息
    const products = [
      {
        id: 1,
        name: '马克杯',
        image: '/images/mug-white.jpg',
        points: 50,
        description: '精美白色陶瓷马克杯，容量350ml，采用环保材质制作，安全无毒。',
        stock: 100,
        category: 'daily',
        categoryName: '生活用品',
        redeemed: 15
      },
      {
        id: 2,
        name: '马克杯',
        image: '/images/mug-teal.jpg',
        points: 60,
        description: '时尚青色马克杯，带拉花图案，容量400ml，采用环保材质制作，安全无毒。',
        stock: 80,
        category: 'daily',
        categoryName: '生活用品',
        redeemed: 12
      },
      {
        id: 3,
        name: '马克杯',
        image: '/images/mug-gold.jpg',
        points: 80,
        description: '金色手柄马克杯，高端品质，容量350ml，采用环保材质制作，安全无毒。',
        stock: 50,
        category: 'daily',
        categoryName: '生活用品',
        redeemed: 8
      },
      {
        id: 4,
        name: '马克杯',
        image: '/images/mug-brown.jpg',
        points: 70,
        description: '棕色陶瓷杯套装，含杯托，容量350ml，采用环保材质制作，安全无毒。',
        stock: 60,
        category: 'daily',
        categoryName: '生活用品',
        redeemed: 10
      },
      {
        id: 5,
        name: '故事集',
        image: '/images/story-book.jpg',
        points: 120,
        description: '遗体捐献者感人故事集，记录真实感人的捐献故事，传递大爱精神。',
        stock: 30,
        category: 'book',
        categoryName: '图书',
        redeemed: 5
      },
      {
        id: 6,
        name: '雨伞',
        image: '/images/umbrella.jpg',
        points: 100,
        description: '定制logo雨伞，防水耐用，采用高品质材料制作，实用美观。',
        stock: 40,
        category: 'daily',
        categoryName: '生活用品',
        redeemed: 6
      }
    ];
    
    const product = products.find(p => p.id == productId);
    if (product) {
      // 设置商品图片
      const productImages = [
        product.image,
        product.image // 这里可以添加更多图片
      ];
      
      console.log('商品信息加载成功:', product);
      this.setData({
        selectedProduct: product,
        productImages: productImages
      });
      
      this.checkRedeemStatus();
    } else {
      console.error('未找到商品信息，商品ID:', productId);
      wx.showToast({
        title: '商品不存在',
        icon: 'none'
      });
    }
  },

  // 检查兑换状态
  checkRedeemStatus() {
    const { selectedProduct, redeemQuantity, userInfo } = this.data;
    if (!selectedProduct) return;
    
    const totalPoints = selectedProduct.points * redeemQuantity;
    const canRedeem = userInfo.currentPoints >= totalPoints && redeemQuantity <= selectedProduct.stock;
    
    this.setData({
      canRedeem: canRedeem
    });
  },

  // 减少数量
  decreaseQuantity() {
    if (this.data.redeemQuantity > 1) {
      this.setData({
        redeemQuantity: this.data.redeemQuantity - 1
      });
      this.checkRedeemStatus();
    }
  },

  // 增加数量
  increaseQuantity() {
    const newQuantity = this.data.redeemQuantity + 1;
    const { selectedProduct, userInfo } = this.data;
    
    // 检查积分和库存
    const totalPoints = selectedProduct.points * newQuantity;
    if (totalPoints <= userInfo.currentPoints && newQuantity <= selectedProduct.stock) {
      this.setData({
        redeemQuantity: newQuantity
      });
      this.checkRedeemStatus();
    } else {
      if (totalPoints > userInfo.currentPoints) {
        wx.showToast({
          title: '积分不足',
          icon: 'none'
        });
      } else {
        wx.showToast({
          title: '库存不足',
          icon: 'none'
        });
      }
    }
  },

  // 开始兑换流程
  startRedeem() {
    console.log('开始兑换流程，canRedeem:', this.data.canRedeem);
    if (!this.data.canRedeem) {
      wx.showToast({
        title: '积分不足或库存不足',
        icon: 'none'
      });
      return;
    }
    
    console.log('准备跳转到兑换流程页面，商品ID:', this.data.selectedProduct.id, '数量:', this.data.redeemQuantity);
    // 跳转到兑换流程页面
    wx.navigateTo({
      url: `/pages/volunteer/redeem-process?productId=${this.data.selectedProduct.id}&quantity=${this.data.redeemQuantity}`,
      success: () => {
        console.log('跳转到兑换流程页面成功');
      },
      fail: (error) => {
        console.error('跳转到兑换流程页面失败:', error);
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        });
      }
    });
  },

  // 图片轮播变化
  onSwiperChange(e) {
    this.setData({
      currentImageIndex: e.detail.current
    });
  },

  // 返回
  goBack() {
    wx.navigateBack();
  },

  // 分享
  onShareAppMessage() {
    return {
      title: `${this.data.selectedProduct.name} - 积分兑换`,
      path: `/pages/volunteer/redeem-flow?productId=${this.data.selectedProduct.id}`,
      imageUrl: this.data.selectedProduct.image
    };
  }
});
